/**
 * 
 */
package com.googlecode.rotools.rodb;

import java.io.Closeable;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;

/**
 * 
 */
 abstract class ResultSetWrapper<T> implements Iterator<T>, Closeable  {
	 private ResultSet resultSet;
	 private boolean next;
	/**
	 * @param resultSet
	 * @throws SQLException 
	 */
	ResultSetWrapper(ResultSet resultSet) throws SQLException {
		super();
		this.resultSet = resultSet;
		next = this.resultSet.next();
	}
	/* (non-Javadoc)
	 * @see java.io.Closeable#close()
	 */
	public void close() throws IOException {
		try {
			resultSet.close();
			
		} catch (SQLException e) {
			throw new IOException(e);
			
		}
	}
	/* (non-Javadoc)
	 * @see java.util.Iterator#hasNext()
	 */
	public boolean hasNext() {
		return next;
	}
	/* (non-Javadoc)
	 * @see java.util.Iterator#next()
	 */
	public T next() {
		T result = null;
		if(next){
			try {
				result = newElement(resultSet);
				next = resultSet.next();
				
			} catch (SQLException e) {
				throw new IllegalStateException(e);
				
			}
		}
		return result;
	}
	/* (non-Javadoc)
	 * @see java.util.Iterator#remove()
	 */
	public void remove() {
		throw new UnsupportedOperationException(this.getClass().getSimpleName() + ".remove()");
		
	}
	abstract T newElement(ResultSet resultSet) throws SQLException;
}
